<?php

declare (strict_types=1);


namespace App\Models\GameDB\Pet;

use App\Models\MainDB\Gift;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class PoolIndependentPrize extends Model
{
    protected $connection = 'mysql_game';
    protected $table = 'lottery_pet_pool_independent_prize';
    //protected $fillable = [];
    protected $guarded = [];

    //protected $casts = ['id' => 'int', 'user_id' => 'integer', 'amount' => 'integer', 'balance' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    public function one(array $filters)
    {
        return self::query()->where($filters)->first();
    }

    public function listAll(array $filters, $fields)
    {
        return self::query()->where($filters)->select($fields)->get();
    }

    public function getGiftListByIds(array $templateIds, array $fields)
    {
        return self::query()->select($fields)->whereIn('id', $templateIds)->get();
    }


    public function updateData(array $filters, array $data)
    {
        return self::query()->where($filters)->update($data);
    }

    public function appendPrizes($poolGroup, Collection $prizeList, $user)
    {
        $insert = [];
        $update = [];
        $pool   = self::query()->where(['independent_id' => $poolGroup->independent_id])->where(['group_id' => $poolGroup->group_id])->get();
        foreach ($prizeList as $prize) {
            $prizeId       = $prize->gift_template_id;
            $templatePrize = $pool->where('gift_template_id', $prizeId)->first();
            if ($templatePrize) { // 奖励存在
                $update[$prizeId] = $prize['count'];
            } else { // 奖励不存在
                $insert[] = ['independent_id' => $poolGroup->independent_id,
                             'group_id'       => $poolGroup->group_id, 'gift_template_id' => $prizeId, 'user_id' => $user->user_id,
                             'count'          => $prize['count'], 'template_count' => $prize['count']];
            }
        }
        if ($insert) {
            self::query()->insert($insert);
        }
        if ($update) {
            $this->batchIncPrizesByGroup($poolGroup, $update);
        }
    }


    // 批量增加礼物数量（抽完补奖池, 额外设置总数）
    public function batchIncPrizesByGroup($poolGroup, array $update)
    {
        if (empty($update)) {
            return true;
        }

        $prizeIds      = array_keys($update);
        $prizeIdsSting = implode(',', $prizeIds);

        $table = $this->getTable();
        $sql   = "update {$table} set ";
        // 增加数量
        $sql .= "`count` = case `gift_template_id`";
        foreach ($update as $prizeId => $prizeCount) {
            $sql .= "when {$prizeId} then `count` + {$prizeCount} ";
        }
        $sql .= "else `count` end, ";
        // 增加总数
        $sql .= "`template_count` = case `gift_template_id` ";
        foreach ($update as $prizeId => $prizeCount) {
            $sql .= "when {$prizeId} then `template_count` + {$prizeCount} ";
        }
        $sql .= "else `template_count` end ";
        // 条件
        $sql .= " where independent_id= '{$poolGroup->independent_id}' and group_id = '{$poolGroup->group_id}' and gift_template_id in ($prizeIdsSting)";

        return DB::connection('mysql_game')->update($sql);
    }

    // 批量减少礼物数量
    public function batchDecPrizesByGroup($poolGroup, array $update)
    {
        if (empty($update)) {
            return true;
        }

        $independentIds = [];
        $groupIds       = [];
        $templateIds    = [];

        $table = $this->getTable();
        $sql   = "update {$table} set  `count` = case ";
        foreach ($update as $independentId => $independentPrize) {
            $independentIds[] = $independentId;
            foreach ($independentPrize as $groupId => $groupPrize) {
                $groupIds[] = $groupId;
                foreach ($groupPrize as $prizeId => $prizeCount) {
                    $templateIds[] = $prizeId;
                    $sql           .= "when `independent_id` = {$independentId}  and group_id = {$groupId} and `gift_template_id` = {$prizeId}
                    then `count` - {$prizeCount} ";
                }
            }
        }
        $independentIdsSting = implode(',', $independentIds);
        $groupIdsSting       = implode(',', $groupIds);
        $templateIdsString   = implode(',', $templateIds);
        $sql                 .= "else `count` end where independent_id in ($independentIdsSting) and group_id in ($groupIdsSting) and gift_template_id in ($templateIdsString)";

        return DB::connection('mysql_game')->update($sql);
    }

    public function getPrizeListWithGift(array $filters, array $fields)
    {
        $query = self::query()->select($fields)->join(app('model_lottery_pet_gift_template')->getTable(),
            'gift_template_id', '=', app('model_lottery_pet_gift_template')->getTable() . ".id");
        return $query->where($filters)->get();
    }


}